<template>
  <div>
    <!-- 标题 -->
    <el-card class="content scrollbar">
      <el-form class="search ml20" :inline="true" label-suffix="：" size="mini">
        <el-form-item label="姓名">
          <el-input
            v-model="search.name"
            clearable
            class="w150"
            placeholder="请输入姓名"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="search.phone"
            clearable
            class="w130"
            maxlength="30"
            placeholder="请输入手机号"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="组织">
          <el-cascader
            v-model="search.deptIds"
            class="w180"
            :props="optionProps"
            :options="options.yard"
            :show-all-levels="false"
            collapse-tags
            clearable
            @change="getList('search')"
          />
        </el-form-item>
        <el-form-item label="三方编码">
          <el-input
            v-model="search.code"
            clearable
            class="w130"
            placeholder="请输入三方编码"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="search.status" @change="getList('search')">
            <el-radio :label="-1">全部</el-radio>
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getList('search')">确认
          </el-button>
          <el-button @click="searchReset">重置
          </el-button>
        </el-form-item>
        <el-form-item class="ml50">
          <el-button v-if="permission['001007008001']" type="primary" @click="detailBtn('新增',{})">新增
          </el-button>
          <!--          <el-button v-if="permission['001007008002']" type="primary" @click="dialogVisible = true">导入
          </el-button>
          <el-button v-if="permission['001007008003']" type="primary" @click="hint('导出','导出该列表')">导出
          </el-button>-->

        </el-form-item>
      </el-form>
      <el-table
        ref="dragTable"
        v-loading="loading"
        :height="tableHeight"
        :data="list"
        size="small"
        :cell-style="$style.cellStyle"
        :header-cell-style="$style.rowClass"
      >
        <!-- <ElTableColumn label="ID" prop="id" /> -->
        <ElTableColumn label="序号" type="index" width="50" />
        <ElTableColumn label="姓名" prop="name" />
        <ElTableColumn label="手机号" prop="phone" width="100" />
        <ElTableColumn label="三方编码" prop="code" />
        <ElTableColumn label="岗位" prop="positionName">
          <template slot-scope="scope">
            <div v-if="scope.row.positionName">
              <el-popover
                v-if="scope.row.positionName.length > 10"
                placement="top-start"
                trigger="hover"
                :content="scope.row.positionName "
              >
                <el-button slot="reference" size="mini" type="text">
                  <span>{{ scope.row.positionName.slice(0, 10)+ "..." }}</span>
                </el-button>
              </el-popover>
              <span v-else>{{ scope.row.positionName }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="人员属性" prop="personType">
          <template slot-scope="{row}">
            <span>{{ row.personType == 1?'总部':'院区' }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="岗位属性" prop="positionAttributeName" />
        <ElTableColumn label="创建方式" prop="createModeName" />

        <ElTableColumn label="所属院区" prop="deptName">
          <template slot-scope="{row}">
            <span>{{ row.yardName }}</span>
            <span v-if="row.deptName">/{{ row.deptName }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建人" prop="createrName" />
        <ElTableColumn label="创建时间" prop="createTime" width="140" />
        <ElTableColumn label="状态" width="80">
          <template slot-scope="{ row }">
            <span v-if="row.status == 1">启用</span>
            <span v-if="row.status == 0">禁用</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" width="160" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              v-if="permission['001007008004']"
              type="primary"
              size="mini"
              @click="detailBtn('修改',row)"
            >修改</el-button>
            <el-button
              v-if="row.status == 0&&permission['001007008005']"
              type="success"
              size="mini"
              @click="hint('启用',`启用${row.name}`,row)"
            >启用
            </el-button>
            <el-button
              v-else-if="permission['001007008005']"
              type="warning"
              size="mini"
              @click="hint('禁用',`禁用${row.name}`,row)"
            >禁用</el-button>
          </template>
        </ElTableColumn>
      </el-table>
      <pagination
        class="page tc mt10"
        :total="page.total"
        :page.sync="page.pageNum"
        :limit.sync="page.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog v-dialogdrag title="导入" :close-on-click-modal="false" :visible.sync="dialogVisible" width="40%">
      <el-form class="search ml20" :inline="true" label-position="right" label-width="100px" size="mini">
        <el-form-item label="下载模板">
          <el-button type="text" class="w500 tl" @click="hint('下载模板',`确定下载模板`)">下载模板</el-button>
        </el-form-item>
        <el-form-item label="选择文件">
          <fileUpload v-if="dialogVisible" file-type="personnel" @getUrl="getFile" />
        </el-form-item>
      </el-form>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="dialogVisible = false">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>

</template>

<script>
import pagination from '@/components/Pagination';
import exportUrl from '@/utils/exportUrl';
import fileUpload from '@/components/Upload/fileUpload';
import { getDeptTree } from '@/api/organization';
import { personList, statusUpdate, personExport } from '@/api/personnel';
import index from '@/mixins/index';
import { mapGetters } from 'vuex';
class Page {
  total = 0;
  pageNum = 1;
  pageSize = 30;
}
class Search {
  name = '';
  phone = '';
  code = '';
  status = -1;
  deptIds = [];
  yardIds = []
}

class Options {
  yard = []
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
}
class Detail {
  name = '';
  positionAttributeIds = '';
  code = '';
}
export default {
  components: {
    pagination,
    fileUpload

  },
  mixins: [index],
  data() {
    return {
      search: new Search(), // 检索条件
      options: new Options(), // 选项
      page: new Page(), // 分页
      detail: new Detail(), // 提交信息
      list: [], // 列表
      url: exportUrl.url,
      dialogVisible: false,
      loading: false,
      fileList: [],
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        multiple: true,
        emitPath: false,
        checkStrictly: true
      },
      tableHeight: 200
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },

  mounted() {
    this.getSearchQuery('search');
    this.getOptions();
    // 初始化表格高度
    this.$nextTick(() => {
      this.initTableHeight();
    });
    window.addEventListener('resize', this.initTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initTableHeight);
  },
  methods: {
    // 初始化表格高度
    initTableHeight() {
      if (!this.$refs.dragTable) {
        this.$nextTick(() => {
          this.initTableHeight();
        });
        return;
      }
      const tableHeight = window.innerHeight - this.$refs.dragTable.$el.getBoundingClientRect().top - 70;
      this.tableHeight = Math.max(tableHeight, 200);
    },
    async getOptions() {
      try {
        const org = await getDeptTree({
          withOutAutoCreate: false
        });
        this.options.yard = org ? this.getTreeData(org.data) : {};
      } catch (e) {
        this.options.org = [];
      }
      // console.log(res);
      this.getList();
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    async getList() {
      this.search.yardIds = this.search.deptIds;
      this.setSearchQuery('search');
      this.loading = true;
      try {
        const { data } = await personList({
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.search
        });
        // console.log(data);
        this.list = data.list;
        this.page.total = data.total;
        this.loading = false;
      } catch (e) {
        this.page.total = 0;
        this.list = [];
        this.loading = false;
      }
    },
    // 搜索重置
    searchReset() {
      this.search = new Search();
      this.getList();
    },
    getFile(e) {
      console.log(e);
    },

    // 详情跳转
    detailBtn(nameType, row) {
      this.$router.push({
        path: '/jurisdiction/personnel/detail',
        query: { nameType: nameType, id: row.id }
      });
    },

    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case '启用':
              this.modifyState('启用', row);
              break;
            case '禁用':
              this.modifyState('禁用', row);
              break;
            case '导出':
              this.export();
              break;
            case '下载模板':
              this.template();
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },

    // 启用禁用
    async modifyState(type, row) {
      let status = row.status == 0 ? 1 : 0;
      // console.log(status);
      let ids = [row.id];
      const res = await statusUpdate({
        ids: ids,
        status: status
      });
      this.$notification('操作成功', 'success', res.msg);
      // this.dialogVisible = false;
      this.getList();

      // console.log(res);
    },
    // 导出
    async export() {
      const res = await personExport({ ...this.search });
      // let url = window.server.SERVER_API[1].excel + res.data;
      // window.open(url);
      // console.log(window.server.SERVER_API[1].excel);

      // this.$notification('操作成功', 'success', res.msg);
    },
    // 下载模板
    async template() {
      let url = window.server.SERVER_API[2].temolate + 'muban/%E4%BA%BA%E5%91%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
      window.open(url);
      // console.log(window.server.SERVER_API[2].temolate);
    }

  }
};
</script>

<style lang="scss" scoped>
.content {
  // height: calc(100% - 56px);
  // overflow-y: hidden;
  // height: 85vh;
  ::v-deep img {
    width: 50px;
    border-radius: 4px;
    margin-top: 6px;
  }
}
.content:hover {
  overflow-y: auto;
}
::v-deep.el-upload {
  position: absolute;
  top: -30px;
  left: 104px;
}
</style>
